<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input v-model="queryParams.ruleName" placeholder="请输入规则名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['dormitory:rule:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['dormitory:rule:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['dormitory:rule:remove']"
              >删除</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['dormitory:rule:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table height="calc(100vh - 370px)" v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="规则名称" align="center" prop="ruleName" />
        <el-table-column label="适用对象" align="center" prop="groupNames" />
        <el-table-column label="考勤时间" align="center" prop="shiftNames" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dormitory:rule:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dormitory:rule:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改考勤规则对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="750px" append-to-body>
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="指定对象" prop="groupIds" required>
          <el-tree-select
            v-model="form.groupIds"
            :data="groupOptions"
            multiple
            :props="{ value: 'id', label: 'label', children: 'children' }"
            default-expand-all
            value-key="id"
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="考勤日设置">
          <el-row style="width: 100%">
            <el-col :span="5">
              <span>工作日</span>
            </el-col>
            <el-col :span="12">
              <span>班次时间段：</span>
              <el-select
                v-model="commonShiftSegment"
                placeholder="更改班次"
                clearable
                style="width: 220px"
                @change="() => ruleShifts.forEach(rs => rs.shiftId = commonShiftSegment)"
              >
                <el-option
                  v-for="dict in shiftSegments"
                  :key="dict.id"
                  :label="dict.shiftName + '：' + dict.shiftSegments"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-divider />
          <el-row style="width: 100%" v-for="rs of ruleShifts" :key="rs.key">
            <el-col :span="5">
              <dict-tag :options="week_dict" :value="rs.effectDate" />
            </el-col>
            <el-col :span="12">
              <el-select v-model="rs.shiftId" placeholder="请选择班次" clearable style="width: 364px">
                <el-option
                  v-for="dict in shiftSegments"
                  :key="dict.id"
                  :label="dict.shiftName + '：' + dict.shiftSegments"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-divider />
          </el-row>
          <el-row style="width: 100%">
            <el-col :span="5">
              <el-button type="primary" size="small" @click="() => { form.includeShifts.push({idx: uuid(), dateType: '2', effectType: '1'}) }" round
                >增加日期</el-button
              >
            </el-col>
            <el-col :span="12">
              <span>可指定某个周末或者节假日里需要打卡</span>
            </el-col>
          </el-row>
          <el-row style="width: 100%; padding-bottom: 5px" v-for="(is,index) of form.includeShifts" :key="index">
            <el-col :span="5">
              <el-date-picker v-model="is.effectDate" type="date" placeholder="请选择日期" style="width: 130px" />
            </el-col>
            <el-col :span="14">
              <el-select v-model="is.shiftId" placeholder="请选择班次" clearable style="width: 344px;margin: 0 10px">
                <el-option
                  v-for="dict in shiftSegments"
                  :key="dict.id"
                  :label="dict.shiftName + ':' + dict.shiftSegments"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="1">
              <el-button
                type="danger"
                size="small"
                circle
                icon="Delete"
                @click="()=>{ form.includeShifts = form.includeShifts.filter(e => e.idx !== is.idx);}"
              />
            </el-col>
          </el-row>
          <el-row style="width: 100%">
            <el-col :span="5">
              <el-button type="primary" size="small" @click="() => { form.excludeShifts.push({idx: uuid(), dateType: '2', effectType: '2'}) }" round
                >排除日期</el-button
              >
            </el-col>
            <el-col :span="12">
              <span>可指定某个日期里不需要打卡</span>
            </el-col>
          </el-row>
          <el-row style="width: 100%; padding-bottom: 5px" v-for="is of form.excludeShifts">
            <el-col :span="5">
              <el-date-picker v-model="is.effectDate" type="date" placeholder="请选择日期" style="width: 130px" />
            </el-col>
            <el-col :span="14">
              <el-select v-model="is.shiftId" placeholder="请选择班次" clearable style="width: 344px;margin: 0 10px">
                <el-option
                  v-for="dict in shiftSegments"
                  :key="dict.id"
                  :label="dict.shiftName + ':' + dict.shiftSegments"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="1">
              <el-button
                type="danger"
                size="small"
                circle
                icon="Delete"
                @click="()=>{ form.excludeShifts = form.excludeShifts.filter(e => e.idx !== is.idx);}"
              />
            </el-col>
          </el-row>
          <el-checkbox true-label="1" false-label="0" v-model="form.followHoliday">法定节假日自动排休</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rule" lang="ts">
import { listRule, getRule, delRule, addRule, updateRule, pageRule } from '@/api/attendance/setting/rule';
import { RuleVO, RuleQuery, RuleForm } from '@/api/attendance/setting/rule/types';
import { groupTreeSelect } from '@/api/attendance/setting/group';
import { listShiftSegments } from '@/api/attendance/setting/shift';
import { uuid } from '@/utils/ruoyi';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { week_dict } = toRefs<any>(proxy?.useDict('week_dict'));

const ruleList = ref<RuleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const shiftSegments = ref([]);
const queryFormRef = ref<ElFormInstance>();
const ruleFormRef = ref<ElFormInstance>();
const groupOptions = ref<any[]>([]);
const commonShiftSegment = ref();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initRuleShifts = [
  {
    key: 1,
    shiftId: undefined,
    shiftSegments: undefined,
    effectDate: 'Monday',
    dateType: '1',
    effectType: '1'
  },
  {
    key: 2,
    shiftId: undefined,
    shiftSegments: undefined,
    effectDate: 'Tuesday',
    dateType: '1',
    effectType: '1'
  },
  {
    key: 3,
    shiftId: undefined,
    shiftSegments: undefined,
    effectDate: 'Wednesday',
    dateType: '1',
    effectType: '1'
  },
  {
    key: 4,
    shiftId: undefined,
    shiftSegments: undefined,
    effectDate: 'Thursday',
    dateType: '1',
    effectType: '1'
  },
  {
    key: 5,
    shiftId: undefined,
    shiftSegments: undefined,
    effectDate: 'Friday',
    dateType: '1',
    effectType: '1'
  },
  {
    key: 6,
    shiftId: undefined,
    shiftSegments: undefined,
    effectDate: 'Saturday',
    dateType: '1',
    effectType: '1'
  },
  {
    key: 7,
    shiftId: undefined,
    shiftSegments: undefined,
    effectDate: 'Sunday',
    dateType: '1',
    effectType: '1'
  }
];
let ruleShifts = ref([...initRuleShifts]);
const initFormData: RuleForm = {
  id: undefined,
  type: 2,
  ruleName: undefined,
  groupIds: [],
  shifts: [],
  includeShifts: [],
  excludeShifts: []
};
const data = reactive<PageData<RuleForm, RuleQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: 2,
    ruleName: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询考勤规则列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageRule(queryParams.value);
  ruleList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 查询部门下拉树结构 */
const getGroupTree = async () => {
  const res = await groupTreeSelect({ groupType: 3 });
  res.data[0]['disabled'] = true;
  groupOptions.value = res.data;
};

const loadShiftSegments = async () => {
  const res = await listShiftSegments({ type: 2 });
  shiftSegments.value = res.data;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  commonShiftSegment.value = undefined;
  shiftSegments.value = [];
  form.value.followHoliday = 0;
  form.value.shifts = [];
  form.value.includeShifts = [];
  form.value.excludeShifts = [];
  for (let s of initRuleShifts) {
    s.shiftId = undefined;
  }
  ruleShifts.value = [...initRuleShifts];
  ruleFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RuleVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getGroupTree();
  loadShiftSegments();
  dialog.visible = true;
  dialog.title = '添加考勤规则';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RuleVO) => {
  reset();
  await getGroupTree();
  await loadShiftSegments();
  const _id = row?.id || ids.value[0];
  const res = await getRule(_id);
  Object.assign(form.value, res.data);
  ruleShifts.value = form.value.shifts;
  dialog.visible = true;
  dialog.title = '修改考勤规则';
};

/** 提交按钮 */
const submitForm = () => {
  ruleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.shifts = ruleShifts.value;
      if (form.value.id) {
        await updateRule(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addRule(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RuleVO) => {
  const _ids = row?.id || ids.value;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.ruleName + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delRule(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/rule/export',
    {
      ...queryParams.value
    },
    `rule_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
